package com.jxw.cloudpen.web.palpay;

import com.alibaba.fastjson.JSONObject;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Refund;
import com.paypal.base.rest.PayPalRESTException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author ligang
 * @create 2025/5/19 15:52
 */
@Controller
@RequestMapping("/paypal")
public class PayPalController {
    @Autowired
    private PayPalService payPalService;


    //    Payment payment = paypalService.createPayment(
//            500.00,
//            "USD",
//            PaypalPaymentMethod.paypal,
//            PaypalPaymentIntent.sale,
//            "payment description",
//            cancelUrl,
//            successUrl);
    @PostMapping("/pay")
//    public String createPayment(@RequestParam("total") Double total,
//                                @RequestParam("currency") String currency,
//                                @RequestParam("method") String method, @RequestParam("intent") String intent,
//                                @RequestParam("description") String description)

    public String createPayment(@RequestBody PayRequest payRequest)
            throws PayPalRESTException, PayPalRESTException {

        String cancelUrl = "http://localhost:8080/paypal/cancel";
        String successUrl = "http://localhost:8080/paypal/success";
//        Payment payment = payPalService.createPayment(total, currency, method, intent, description, cancelUrl, successUrl);
        Payment payment = payPalService.createPayment(payRequest.getTotal(), payRequest.getCurrency(),
                payRequest.getMethod(), payRequest.getIntent(), payRequest.getDescription(), cancelUrl, successUrl);

        String captureId = payment.getTransactions().get(0).getRelatedResources().get(0).getCapture().getId();

        for (Links link: payment.getLinks()) {
            if (link.getRel().equals("approval_url")) {
                return "redirect:" + link.getHref();
            }
        }
        return "redirect:/";
    }
    @GetMapping("/success")
    public String paymentSuccess(@RequestParam("paymentId") String paymentId, @RequestParam("payerId") String payerId) throws PayPalRESTException {

        Payment payment = payPalService.executePayment(paymentId, payerId);

        if (payment.getState().equals("approved")) {
            return "paymentSuccess";
        }
        return "paymentError";
    }

    @GetMapping("/cancel")
    public String paymentCancel() {
        return "paymentCancel";
    }


    @PostMapping("/refund")
    public String processRefund(
            @RequestParam String captureId,
            @RequestParam String amount,
            @RequestParam String currency) {

        try {
            Refund refund = payPalService.refundPayment(captureId, amount, currency);
            refund.getId();
            return JSONObject.toJSONString(refund);
        } catch (PayPalRESTException e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body(new ErrorResponse("退款处理失败: " + e.getMessage()));
            return JSONObject.toJSONString(e.getMessage());
        }
    }

    @GetMapping("/refund/{refundId}")
    public String getRefund(@PathVariable String refundId) {
        try {
            Refund refund = payPalService.getRefundDetails(refundId);
//            refund.getState();completed
            return JSONObject.toJSONString(refund);
        } catch (PayPalRESTException e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body(new ErrorResponse("获取退款详情失败: " + e.getMessage()));
            return JSONObject.toJSONString(e.getMessage());
        }
    }

}
